#pragma once

#include "log.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unordered_map>

// using func_t = std::function<std::string(const std::string&)>;
typedef std::function<std::string(const std::string &)> func_t;

Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t default_port = 8080;
std::string default_ip = "0.0.0.0";
const int size = 1024;

class UdpServer
{

public:
    UdpServer(const uint16_t &port = default_port, const std::string &ip = default_ip)
        : _sockfd(0), _port(port), _ip(ip), _isrunning(false)
    {
    }

    void Init()
    {
        // 1.创建udp socket
        // 2.Udp的socket是全双工的，允许被同时读写的
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "socket create error,sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success,sockfd: %d", _sockfd);

        // 2.bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);                  // 需要保证我们的端口号是网络字节序列，因为端口号是要给对方发送的
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // string->unit32_t 必须是网络序列，可通过函数转换不需手动转换了

        if (bind(_sockfd, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error,errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport)
    {
        auto iter = _online_user.find(clientip);
        if (iter == _online_user.end())
        {
            _online_user.insert({clientip, client});
            std::cout << "[" << clientip << " : " << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string &info, const std::string clientip, uint16_t clientport)
    {
        for (const auto &user : _online_user)
        {
            std::string message = "[";
            message += clientip;
            message += " : ";
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, message.c_str(), message.size(), 0, (const sockaddr *)(&user.second), len);
        }
    }

    // void Run(func_t func) // 对代码进行分层解耦
    void Run()
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            memset(inbuffer,0,sizeof(inbuffer));
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Waring, "recvfrom error,errno: %d,err string: %s", errno, strerror(errno));
                continue;
            }

            // inbuffer[n] = 0;
            // std::string info = inbuffer;
            // std::string echo_string = func(info);
            // sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (const sockaddr *)&client, len);

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);

            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);
        }
    }

    ~UdpServer()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;     // 网络文件描述符
    std::string _ip; // 任意ip地址 0
    uint16_t _port;  // 表示服务器进程端口号
    bool _isrunning;
    std::unordered_map<std::string, struct sockaddr_in> _online_user;
};
